package userService

import (
	"chart.zozoo.net/app/dao/usersDao"
	"chart.zozoo.net/app/dao/usersOnlineDao"
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/app/utils/commonFunc"
	"chart.zozoo.net/core/conf"
	"chart.zozoo.net/core/mysql"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"time"
)

type RegisterParams struct {
	UserName string `json:"username" binding:"required,len=11"`
	Password string `json:"password" binding:"required,min=6,max=32"`
	Ip       string `json:"ip"`
}

func (r *RegisterParams) Register() (id int, err error) {
	u := &models.Users{
		Username: r.UserName,
		Password: r.Password,
	}

	//匹配手机号
	status, err := commonFunc.MatchMobile(r.UserName)
	if err != nil {
		return
	}
	if !status {
		return 0, errors.New("手机号格式错误")
	}

	//查询用户数是否存在
	res := mysql.MysqlClient.Select("id").
		Where("username = ?", r.UserName).
		First(u)
	if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
		return 0, err
	}
	if u.Id > 0 {
		return 0, errors.New("用户名冲突")
	}

	//加密密码
	u.Password, err = u.HashPwd(u.Password)
	if err != nil {
		return 0, err
	}

	//生成uuid
	u.Uuid = uuid.New().String()

	//获取IP定位
	ipRes, err := commonFunc.IpLocation("117.188.113.170")
	if err != nil {
		return 0, err
	}
	u.City = ipRes.AdInfo.City
	u.Profile = "有志者，事竟成"

	//开启事务
	tx := mysql.MysqlClient.Begin()

	//创建用户
	err = usersDao.Create(u, tx)
	if err != nil {
		tx.Rollback()
		return
	}

	//创建用户在线情况
	online := &models.UserOnline{
		Uuid:      u.Uuid,
		Host:      conf.Conf.Server.Host,
		Addr:      "",
		CreatedAt: time.Now(),
		LoginAt:   time.Now(),
		LogoutAt:  time.Now(),
	}
	err = usersOnlineDao.Create(online, tx)
	if err != nil {
		tx.Rollback()
		return
	}

	//提交事务
	tx.Commit()

	return u.Id, nil
}
